var superInput = {
	/*
		@初始化
	*/
	init: function(dataCache){
		var _this = this;
		_this.tagsData = {
			tagNames : dataCache.tagNames,
			tagVals  : dataCache.tagVals
		}
		//_this.productType = dataCache.connectionObject.productType;
		_this.productType = "";
		var superInputName = '';
		_this.createDOM(_this.productType);
		_this.bindAllEvent();
		$.each($('div[super-input-warp]'), function( i, v ){
			superInputName = v.getAttribute('super-input-warp');
			_this.dataFill( superInputName, dataCache[superInputName] || [] );
		});
	}
	/*
		@获取标签项数据
		$.callback: 回调
	*/
	,getTagNameData: function(callback){
		var _this = this;
		_this.tagsData = {
			tagNames : [{"id":1,"supportAdSet":1,"supportAdCamp":1,"supportAdGroup":1,"name":I18N.getText("createAd",'countryCode')},{"id":2,"supportAdSet":1,"supportAdCamp":1,"supportAdGroup":1,"name":I18N.getText("createAd",'appName')},{"id":3,"supportAdSet":1,"supportAdCamp":1,"supportAdGroup":1,"name":I18N.getText("createAd",'sex')},{"id":4,"supportAdSet":1,"supportAdCamp":1,"supportAdGroup":1,"name":I18N.getText("createAd",'age')},{"id":5,"supportAdSet":1,"supportAdCamp":1,"supportAdGroup":1,"name":I18N.getText("createAd",'platform')},{"id":6,"supportAdSet":1,"supportAdCamp":1,"supportAdGroup":1,"name":I18N.getText("createAd",'bidType')},{"id":7,"supportAdSet":1,"supportAdCamp":1,"supportAdGroup":1,"name":I18N.getText("createAd",'date')},{"id":8,"supportAdSet":1,"supportAdCamp":1,"supportAdGroup":1,"name":I18N.getText("createAd",'materialType')},{"id":9,"supportAdSet":1,"supportAdCamp":1,"supportAdGroup":1,"name":I18N.getText("createAd",'materialName')},{"id":10,"supportAdSet":1,"supportAdCamp":1,"supportAdGroup":1,"name":I18N.getText("createAd",'creator')},{"id":11,"supportAdSet":1,"supportAdCamp":1,"supportAdGroup":1,"name":I18N.getText("createAd",'appSimpleName')},{"id":12,"supportAdSet":1,"supportAdCamp":1,"supportAdGroup":1,"name":I18N.getText("createAd",'price')},{"id":13,"supportAdSet":1,"supportAdCamp":1,"supportAdGroup":1,"name":I18N.getText("createAd",'uniqueNO')}]
			,tagVals:{"2":"Baidu_Browser","10":"sisi0722","8":"banner","7":"0824","11":"BDR","5":"google_play"}
		}
		typeof callback == 'function' ? callback() : '';
	}
	/*
		@渲染DOM节点	
	*/
	,createDOM: function(_productType){
		var _this = this;
		var superInputList = $('div[super-input]'),
			superInputHtml = '';
		$.each(superInputList, function( index, element ){
			var _seqN = $(element).attr("super-input-warp");
			if (_seqN == "adGroupSeq" && _productType  == 'outlink'){
				$(element).addClass("disabled");
				$(element).removeAttr('focus-now');
			} else {
				$(element).removeClass("disabled");
			}
			superInputHtml  = '';
			if(_this.tagsData){
				superInputHtml += '<ul>';
				$.each(_this.tagsData.tagNames, function(i, v){
					if ((_seqN == "websiteSeq" && v.supportWebsite) || (_seqN == "adCampSeq" && v.supportAdCamp)
					     || (_seqN == "adSetSeq" && v.supportAdSet) || (_seqN == "adGroupSeq" && v.supportAdGroup)
						|| (_seqN == "dpaAdwordSeq" && v.supportDpaAdword) || (_seqN == "dpaTitleSeq" && v.supportDpaTitle)
						|| (_seqN == "dynamicMsgLinkDescSeq" && v.supportDpaDynamicMsg)
					) {
						superInputHtml += '<li tag-id="' + v.id + '" tag-tag="' + v.tag +  '"class="tags-element" title="'
							+ (_this.tagsData.tagVals[v.id] || v.name) + '">'
							+ v.name
							+ '</li>';
					}
				});
				superInputHtml  += '</ul>';
			}
			$(element).find('.select-tags').html(superInputHtml);
		});
	}
	/*
		@绑定全部事件
	*/
	,bindAllEvent: function(){
		var _this = this;
		var _selectTags = $('.select-tags'); //可选标签		
		
		//绑定选择标签事件
		$('li[tag-id]', _selectTags).unbind('click');
		$('li[tag-id]', _selectTags).bind('click', function(){
			var _superInputWarp = $(this).parents('[super-input-warp]');
			if (_superInputWarp.hasClass("disabled")){
				return false;
			}
			var _tagNow = this;
			var _focusNow  = _superInputWarp.find('.selected-tag');
			
			//特殊验证：多图广告模式下存在多个素材
			if(this.getAttribute('tag-id') == 9 && _this.tagsData.adImagesGroup && _this.tagsData.adImagesGroup.length > 0 && _focusNow.length == 1){
				if(window.confirm(I18N.getText('createAd', 'selectedMultipleAds'))){
					_focusNow.attr('focus-now', 'this');
					selectTagToFocus(_tagNow);
					$(this).dialog('close');
				}else{
					_focusNow.attr('focus-now', 'this');
					$(this).dialog('close');
				}
			}else{
				selectTagToFocus(_tagNow)
			}
		});
		//选择标签功能
		function selectTagToFocus(_obj_){
			var _focusNow       = $(_obj_).parents('[super-input-warp]').find('.selected-tag'),
				_choicesList    = $('.choices-list', _focusNow),
				_allLi          = $('> li', _choicesList),
				_tagElement     = $('.tag-element', _choicesList),
				_choicesLi      = $('> li.choices-text', _choicesList),
				_prevli         = _choicesLi.index() == 0 ? [] : _allLi.eq(_choicesLi.index() - 1),
				_choicesText    = $('input', _choicesLi);
			if(!_focusNow || _focusNow.length == 0){
				return false;
			}
			if($.trim(_choicesText.val()) != ''){
				_choicesLi.before('<li class="tag-text">'+ _choicesText.val() +'</li>');
				_choicesText.val('');
				_prevli = _choicesLi.index() == 0 ? [] : _allLi.eq(_choicesLi.index() - 1);
			}
			var _tagHtml = '';
			if(_prevli.length == 1 && !_prevli.hasClass('tag-spacing')){
				_tagHtml += '<li class="tag-spacing">_</li>';
			}
			_tagHtml += '<li class="tag-element" tag-id="'+ _obj_.getAttribute('tag-id')+'" tag-tag="' + _obj_.getAttribute('tag-tag') + '" title="'
					 + _obj_.getAttribute('title')+'">'
					 + _obj_.innerHTML
					 + '</li>';
		
			_choicesLi.before(_tagHtml);
			var _w = _focusNow.width() - _choicesLi.get(0).offsetLeft - _focusNow.css('padding-left').split('px')[0];
			if(_w < 20){
				_w = 20;
			}
			_choicesText.width(inputWidth(_choicesText.val()));
			_choicesText.css('max-width', _w);
			_choicesText.trigger('focus');						
		}
		
		//名称区域鼠标点击事件
		$('.selected-tag').unbind('click');
		$('.selected-tag').bind('click', function(e){
			var _superInputWarp = $(this).parents('[super-input-warp]');
			if (_superInputWarp.hasClass("disabled")){
				return false;
			}

			var _focusNow   = $(this),
				_choicesList= $('.choices-list', _focusNow),
				_choicesLi  = $('li.choices-text', _choicesList),
				_choicesText= $('input', _choicesLi);
			_selectTags.attr('focus-now', _focusNow.attr('id'));
			$('li:last', _choicesList).hasClass('tag-spacing') ? $('li:last', _choicesList).remove() : '';
			//如果事件源与 li:click 重叠，则直接跳出
			if(e.target.tagName != 'DIV' && e.target.tagName != 'UL'){
				_choicesText.trigger('focus');
				return false;
			}
			if($.trim(_choicesText.val()) != ''){
				_choicesLi.before('<li class="tag-text">'+ _choicesText.val() +'</li>');
				_choicesText.val('');
			}
			_choicesList.append(_choicesLi);
			_choicesText.width(inputWidth(_choicesText.val()));
			var _w = _focusNow.width() - _choicesLi.get(0).offsetLeft - _focusNow.css('padding-left').split('px')[0];
			if(_w < 20){
				_w = 20;
			}
			_choicesText.css('max-width', _w); 
			_choicesText.trigger('focus');
		});
		//名称区域-点选已生成tag事件
		$('.selected-tag').off('click', 'li');
		$('.selected-tag').on('click', 'li', function(){
			var _superInputWarp = $(this).parents('[super-input-warp]');
			if (_superInputWarp.hasClass("disabled")){
				return false;
			}

			var _tagLi = $(this),
				_choicesList = _tagLi.parents('.choices-list').eq(0)
			var _choicesLi = $('.choices-text', _choicesList),
				_choicesText= $('input', _choicesLi);
			if(_tagLi.next().get(0) == _choicesLi.get(0)){
				return;
			}
			if($.trim(_choicesText.val()) != ''){
				_choicesLi.prev().length == 1 && !_choicesLi.prev().hasClass('tag-spacing')
					? _choicesLi.before('<li class="tag-spacing">_</li>') : '';
				_choicesLi.next().length == 1 && !_choicesLi.next().hasClass('tag-spacing')
					? _choicesLi.after('<li class="tag-spacing">_</li>') : '';
				_choicesLi.before('<li class="tag-text">'+ _choicesText.val() +'</li>');
			}
			_choicesText.val('');
			_choicesText.width(inputWidth(_choicesText.val()));
			_tagLi.after(_choicesLi);
		});
		//获取当前input文本宽度
		function inputWidth(text){ 
			var sensor = $('<pre>'+ text +'</pre>').css({display: 'none'}); 
			$('body').append(sensor); 
			var width = sensor.width();
			sensor.remove();
			return width + 10;
		};
		//绑定聚焦事件
		$('body').off('keydown click', 'div[super-input-warp]');     
		$('body').on('keydown click', 'div[super-input-warp]', function(){
			if ($(this).hasClass("disabled")){
				return false;
			}

			var _nowInputText = $('.choices-text input', this)
		//	$('.choices-text input').hide();
		//	_nowInputText.show();
			_nowInputText.focus();
			$('[focus-now]').removeAttr('focus-now');
			$(this).attr('focus-now', 'this');
			return;
		});   
		//绑定名称区域失焦事件		
		$('body').off('mousedown', '[super-input-warp!=]');     
		$('body').on('mousedown', '[super-input-warp!=]', function(){
			var _superInputWarp = $(this).parents('div[super-input-warp]');
			if (_superInputWarp.hasClass("disabled")){
				return false;
			}

			if(_superInputWarp.length > 0){
				return false;
			}
			$('[focus-now]').removeAttr('focus-now');
		});
		//名称区键盘事件
		$('.selected-tag').unbind('keydown');
		$('.selected-tag').bind('keydown', function(e){
			var _superInputWarp = $(this).parents('div[super-input-warp]');
			if (_superInputWarp.hasClass("disabled")){
				return false;
			}

			var _focusNow       = $('[super-input-warp][focus-now]'),
				_choicesList    = $('.choices-list', _focusNow),
				_choicesLi      = $('> li.choices-text', _choicesList),
				_prevli         = _choicesLi.prev(), 
				_choicesText    = $('input', _choicesLi);
			//事件源为不backspace并且input文本为空：创建新节点   
			if(e.keyCode !== 8 && _choicesText.val() == ''){  
				_choicesLi.prev().length == 1 && !_choicesLi.prev().hasClass('tag-spacing') 
					? _choicesLi.before('<li class="tag-spacing">_</li>') : '';
				_choicesLi.next().length == 1 && !_choicesLi.next().hasClass('tag-spacing')
					? _choicesLi.after('<li class="tag-spacing">_</li>') : '';
				//_prevli = _choicesLi.prev();
			}
			//事件源为backspace 且input文本为空 且input前一个节点存在:删除input前一个节点
			else if(e.keyCode === 8 && $.trim(_choicesText.val()) === '' && _prevli.length == 1){
				_choicesLi.next().length == 1 && _choicesLi.next().hasClass('tag-spacing')
					? _choicesLi.next().remove() : '';
				_prevli.hasClass('tag-spacing') ? _prevli.prev().remove() : '';
				_prevli.remove();
			}
			var _w = 0;
			if (_choicesLi.length != 0 && undefined != _choicesLi.get(0).offsetLeft){
				 _w = _focusNow.width() - _choicesLi.get(0).offsetLeft - _focusNow.css('padding-left').split('px')[0];
			}
			if(_w < 20){
				_w = 20;
			}
			_choicesText.width(inputWidth(_choicesText.val()));
			_choicesText.css('max-width', _w); 
		});
		$('.selected-tag').unbind('keyup');
		$('.selected-tag').bind('keyup', function(e){
			var _superInputWarp = $(this).parents('div[super-input-warp]');
			if (_superInputWarp.hasClass("disabled")){
				return false;
			}

			var _focusNow       = $('[super-input-warp][focus-now]'),
				_choicesList    = $('.choices-list', _focusNow),
				_choicesLi      = $('> li.choices-text', _choicesList),
				_prevli         = _choicesLi.prev(), 
				_choicesText    = $('input', _choicesLi);

			//事件源为backspace 且input文本为空 且input前一个节点存在:删除input前一个节点
			if(e.keyCode === 8 && $.trim(_choicesText.val()) === '' && _prevli.length == 1){
				_prevli.remove();
			}
			var _w = 0;
			if (undefined != _choicesLi.get(0).offsetLeft){
				_w = _focusNow.width() - _choicesLi.get(0).offsetLeft - _focusNow.css('padding-left').split('px')[0];
			}
			if(_w < 20){
				_w = 20;
			}
			_choicesText.width(inputWidth(_choicesText.val()));
			_choicesText.css('max-width', _w);
		});
	}
	/*
		@获取数据
	*/
	,getData : function(_dom_){
		var seqArray = [];
		$.each($('.tag-element, .tag-text, .choices-text', _dom_), function(i, v){
			//当前是标签
			if(v.getAttribute('class') == 'tag-element'){
				seqArray.push({
					type :'tag',
					tag  : v.getAttribute('tag-tag'),
					tagName : $(v).text()
				});
			}
			//当前是文本
			else if(v.getAttribute('class') == 'tag-text'){
				seqArray.push({
					type :'text',
					text  : $(v).text()
				});
			}
			//当前是输入框
			else if(v.getAttribute('class') == 'choices-text' && $.trim(v.getElementsByTagName('input')[0].value) != ''){
				seqArray.push({
					type :'text',
					text  : v.getElementsByTagName('input')[0].value
				});
			}                    
		});
		return seqArray;
	}
	/*
		@数据回显
		$._superInputName_: 当前数据所对应的input
		$._data_： 回显数据,如果为<1、空；2、空数组；3、其它判定结果为false的>则等同于清空操作
	*/
	,dataFill: function(_superInputName_, _data_){		
		var _this = this;		
		var _data_ = _data_ ? _data_ : []; 
		var _superInputWarp = $( 'div[super-input-warp="'+ _superInputName_ +'"]' );
		if( !_superInputWarp || _superInputWarp.length == 0 ){
			return false;
		}	
		$( '.choices-list', _superInputWarp ).html( '<li class="choices-text"><input type="text"></li>' );//清除原有数据
		var _choicesList    = $( '.choices-list', _superInputWarp ),
			_choicesLi = $( '> li.choices-text', _choicesList );
		_choicesLi.before( createHtml( _data_ ) );
		
		//数据回显生成html片段
		function createHtml(_seq_){
			var _tmpHtml = '';
			$.each(_seq_, function(i, v){                        
				if(i !== 0){
					_tmpHtml += '<li class="tag-spacing">_</li>';
				}
				if(v.type == 'tag'){
					_tmpHtml  += '<li class="tag-element" tag-id="'+ i +'" tag-tag="'+ v.tag +'" title="'+ (_this.tagsData.tagVals[v.tag] || v.tagName)+'">'
					+ v.tagName 
					+ '</li>';
				}
				if(v.type == 'text'){
					_tmpHtml += '<li class="tag-text">'+ v.text +'</li>';
				}   
			});
			return _tmpHtml;
		}
	}
}
//superInput.init();
